<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Client Home</title>
  <style>
    body {
      font-size: 12px;
    }

    .info {
      color: blue;
    }

    .error {
      color: red;
    }
  </style>
</head>

<body>
  <h1>Client Chat</h1>
  username: <input type="text" id="username"><button id="btn-connect">connect</button>
  <button id="btn-close">close</button>
  <button id="btn-clear-log">clear log</button>

  <div>
    message: <input type="text" id="message"> <button id="btn-send">send broadcast</button>
    <button id="btn-send-message-to">send message to user</button>
  </div>
  <table style="width: 100%;">
    <tr>
      <td style="width: 50%; vertical-align: top;">
        <h2>日志</h2>
        <div id="log-container"></div>
      </td>
      <td style="vertical-align: top;">
        <h2>用户列表：</h2>
        <button id="btn-battle">battle</button>
        <select style="width: 100%;" name="onelineuser" id="onlineuser">
        </select>
      </td>
    </tr>
  </table>

  <script>
    let ws = null
    let currentUser = null
    window.onload = function () {
      document.querySelector('#btn-connect').addEventListener('click', ws_init)
      document.querySelector('#btn-close').addEventListener('click', ws_close)
      document.querySelector('#btn-send').addEventListener('click', send_msg)
      document.querySelector('#btn-clear-log').onclick = function () {
        document.querySelector('#log-container').innerHTML = ''
      }
      document.querySelector('#btn-battle').addEventListener('click', user_battle)
      document.querySelector('#btn-send-message-to').addEventListener('click', send_to_user)
    }

    function get_selected_oneline_user() {
      var onlineuser = document.querySelector('#onlineuser')
      console.log(onlineuser.selectedIndex)
      username = onlineuser.options[onlineuser.selectedIndex].value
      return username
    }

    function send_to_user() {
      username = get_selected_oneline_user()
      if(username.length === 0) {
        alert('请选择要发送的用户')
        return
      }
      cmd = {
        Type: "SINGLE-CHAT",
        Data: "你好啊",
        Arg: username
      }
      ws_send_data(cmd)
    }

    function ws_send_data(cmd) {
      if (!ws) {
        alert('未初始化ws')
        return
      }
      if (!cmd) {
        alert('cmd为空.')
        return
      }
      var json = JSON.stringify(cmd);
      console.log('ws send data:', json)
      ws.send(json)
    }

    function user_battle() {
      username = get_selected_oneline_user()
      if (username === currentUser) {
        alert('不能向自己发出Battle')
      }
      var cmd = {
        Type: "BATTLE",
        Arg: username,
        Data: `用户:${username}向你发出Battle`
      }
      ws_send_data(cmd)
    }

    function send_msg() {
      let msg = document.querySelector('#message').value
      if (msg.length === 0) {
        alert('请输入消息内容')
        return
      }
      let data = {
        Type: 'BROADCAST',
        Data: 'hi all: ' + msg,
        Arg: ''
      }
      console.log('send data', data)

      ws_send_data(data)
    }

    function ws_close() {
      if (!ws) {
        alert('ws is null')
        return
      }
      ws.close()
    }

    function ws_init() {
      if (ws) {
        alert('ws is not null')
        return
      }
      let username = document.querySelector('#username').value
      if (username.length === 0) {
        alert('请输入username')
        return
      }
      ws = new WebSocket('ws://localhost:8080/ws?username=' + encodeURIComponent(username))

      ws.onopen = function () {
        currentUser = username
        printLog('Opened')
      }
      ws.onclose = function () {
        printLog('Closed')
        document.querySelector('#onlineuser').innerHTML = ""
        ws = null
        currentUser = null
      }
      ws.onerror = function (e) {
        console.error(e)
        printLog('Error:' + e.data, 'error')
        ws = null
        currentUser = null
      }
      ws.onmessage = function (e) {
        let messages = e.data.split('\n')
        let jsonObj = JSON.parse(messages)
        console.log("recv data:", jsonObj)
        handleMessage(jsonObj)
      }
    }

    function handleMessage(msgObject) {
      if (messageHandler[msgObject.Type]) {
        messageHandler[msgObject.Type](msgObject)
      } else {
        printLog("未知命令：" + JSON.stringify(msgObject), 'error')
      }
    }

    let messageHandler = {
      'BROADCAST': function (data) {
        printLog(data.Data)
        if (data.Arg) {
          var html = []
          data.Arg.forEach((s, i) => {
            if (s !== currentUser) {
              html.push(`<option value="${s}">`)
              html.push(s)
              html.push("</option>")
            }
          })
          document.querySelector('#onlineuser').innerHTML = html.join("")
        }
      },
      'BATTLE': function (data) {
        printLog(data.Data)
      },
      'ERROR': function (data) {
        printLog(data.Data, 'error')
      },
      'SINGLE-CHAT': function(data) {
        alert(`您收到用户:[${data.Arg}]的私信`)
        printLog(data.Data)
      }
    }

    function printLog(log, css = 'info') {
      let oldLog = document.querySelector('#log-container').innerHTML
      oldLog = `<p class="${css}">${new Date().toLocaleTimeString()}: ${log}</p>` + oldLog
      document.querySelector('#log-container').innerHTML = oldLog
    }
  </script>
</body>

</html>